package com.decent.ejfadmin.tools;

import com.decent.ejfadmin.utils.EjfHttpclient;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;

import java.io.File;
import java.io.InputStream;
import java.util.Properties;

/**
 * 邮件发送
 *
 * @author pc_tang
 */
public class EmailSend {
    private static String api_user = "postmaster";
    private static String api_key = "svyIC8rV";
    private static String from = "postmaster";
    private static String url = "https://";


    static {
        try {
            Properties prop = new Properties();
            InputStream in = EmailSend.class.getClassLoader().getResourceAsStream("emailSend.properties");
            prop.load(in);

            api_user = prop.getProperty("api_user").trim();
            api_key = prop.getProperty("api_key").trim();
            from = prop.getProperty("from").trim();
            url = prop.getProperty("url").trim();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 带附件邮件发送
     *
     * @param fileUrl 邮件地址
     * @param to      收邮件
     * @param subject 发送标题
     * @param html    发送内容
     */
    public static void send(String fileUrl, String to, String subject, String html) {
        try {
            File file1 = new File(fileUrl);
            Part[] parts = {new FilePart("files", file1),
                    new StringPart("api_user", api_user),
                    new StringPart("api_key", api_key),
                    new StringPart("from", from),
                    new StringPart("to", to),
                    new StringPart("subject", subject, "UTF-8"),
                    new StringPart("html", html, "UTF-8")};
            EjfHttpclient.Post(url, parts, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 邮件发送
     *
     * @param to      收邮件
     * @param subject 发送标题
     * @param html    发送内容
     */
    public static boolean send(String to, String subject, String html) {
        try {

            Part[] parts = {
                    new StringPart("api_user", api_user),
                    new StringPart("api_key", api_key),
                    new StringPart("from", from),
                    new StringPart("to", to),
                    new StringPart("subject", subject, "UTF-8"),
                    new StringPart("html", html, "UTF-8")};
            String post = EjfHttpclient.Post(url, parts, "UTF-8");
            return post.contains("<message>success</message>");
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
